package com.storage.system.service.impl;

import com.storage.common.core.domain.ServiceResponse;
import com.storage.common.core.page.TableDataInfo;
import com.storage.common.core.text.Convert;
import com.storage.common.enums.OwnerType;
import com.storage.common.enums.RoleType;
import com.storage.common.jpush.JiGuangPushUtil;
import com.storage.system.domain.*;
import com.storage.system.mapper.*;
import com.storage.system.service.IStorageAccountRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * 付款记录 服务层实现
 *
 * @author ruoyi
 * @date 2019-09-20
 */
@Service
public class StorageAccountRecordServiceImpl implements IStorageAccountRecordService {

    @Autowired
    private StorageAccountRecordMapper storageAccountRecordMapper;

    @Autowired
    private StorageUserAgentMapper storageUserAgentMapper;

    @Autowired
    private StorageNoticeMessageMapper storageNoticeMessageMapper;

    @Autowired
    private StorageUserMapper storageUserMapper;

    @Autowired
    private StorageShopMapper storageShopMapper;

    /**
     * 查询付款记录信息
     *
     * @param id 付款记录ID
     * @return 付款记录信息
     */
    @Override
    public StorageAccountRecord selectStorageAccountRecordById(Long id) {
        return storageAccountRecordMapper.selectStorageAccountRecordById(id);
    }

    /**
     * 查询付款记录列表
     *
     * @param storageAccountRecord 付款记录信息
     * @return 付款记录集合
     */
    @Override
    public ServiceResponse<TableDataInfo> selectStorageAccountRecordList(StorageAccountRecord storageAccountRecord, Integer pageNum, Integer pageSize) {
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }

        Integer start = (pageNum - 1) * pageSize;
        // StorageCategory
        List<StorageUser> users = storageAccountRecordMapper.queryPageList(storageAccountRecord, start, pageSize);
        // 查询totalCount
        Long totalCount = storageAccountRecordMapper.queryPageCount(storageAccountRecord);
        if (users == null) {
            return null;
        }

        TableDataInfo pageList = new TableDataInfo(users, totalCount, pageNum, pageSize);
        return new ServiceResponse<>(true, pageList, null);
    }

    /**
     * 新增付款记录
     *
     * @param record 付款记录信息
     * @return 结果
     */
    @Override
    public ServiceResponse<StorageAccountRecord> insertStorageAccountRecord(StorageUser user, StorageAccountRecord record) {
        storageAccountRecordMapper.insertStorageAccountRecord(record);
        // 对应的上下级管理的结算金额也需要扣除
        String type = record.getType() == 1 ? OwnerType.AGENT.name() : OwnerType.SHOP.name();

        StorageUserAgent agent = storageUserAgentMapper.selectUserAgent(record.getAgentId(), record.getUserId(), 1, type);
        BigDecimal subtract = agent.getPaymentMoney().subtract(record.getMoney());
        agent.setPaymentMoney(subtract);

        StorageUserAgent down = storageUserAgentMapper.selectUserAgent( record.getUserId(),record.getAgentId(), 2, type);
        BigDecimal add = down.getPaymentMoney().add(record.getMoney());
        down.setPaymentMoney(add);

        if (!subtract.add(add).equals(new BigDecimal(0))) {
            return new ServiceResponse<>(false, null, "账目计算金额异常");
        }

        storageUserAgentMapper.updateStorageUserAgent(agent);
        storageUserAgentMapper.updateStorageUserAgent(down);

        // 推送极光消息并插入系统提醒消息表
        StorageUser sendNoticeUser = null;
        if (record.getType() == 1) {
            // 下级代理商线下货款
            sendNoticeUser = storageUserMapper.selectStorageUserById(record.getUserId());
        } else {
            // 直营店铺的线下货款给店长推送
            sendNoticeUser = storageUserMapper.selectStorageUserByShopIdRole(record.getUserId(), RoleType.SHOW_LEADER.getValue());
            if (sendNoticeUser == null) {
                // 店长不存在 不进行推送 - 直接返回
                return new ServiceResponse<>(true, selectStorageAccountRecordById(record.getId()), null);
            }
        }
        String phone = sendNoticeUser.getPhone();
        Long userId = sendNoticeUser.getId();
        String title = String.format("代理商已成功收到您线下给的货款 %s 元，请前往查看", record.getMoney());
        StorageNoticeMessage noticeMessage = new StorageNoticeMessage(userId, phone, null, title);
        int result = storageNoticeMessageMapper.insertStorageNoticeMessage(noticeMessage);
        if (result == 1) {
            // 查询系统消息的同时并极光推送
            JiGuangPushUtil.pushNotice(phone, title, null, noticeMessage.getId());
        }

        return new ServiceResponse<>(true, selectStorageAccountRecordById(record.getId()), null);
    }

    /**
     * 修改付款记录
     *
     * @param storageAccountRecord 付款记录信息
     * @return 结果
     */
    @Override
    public int updateStorageAccountRecord(StorageAccountRecord storageAccountRecord) {
        return storageAccountRecordMapper.updateStorageAccountRecord(storageAccountRecord);
    }

    /**
     * 删除付款记录对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteStorageAccountRecordByIds(String ids) {
        return storageAccountRecordMapper.deleteStorageAccountRecordByIds(Convert.toStrArray(ids));
    }

}
